package org.lztvn.elearning.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.lztvn.elearning.entities.Response;
import org.lztvn.elearning.entities.Topic;

public class ResponseDaoImpl implements IResponseDao{
	@PersistenceContext
	private EntityManager em;
	@Override
	public Long addResponse(Response r) {
		em.persist(r);
		return r.getIdResponse();
	}

	@Override
	public void deleteResponse(Long idResponse) {
		Response r = em.find(Response.class, idResponse);
		em.remove(r);
	}

	@Override
	public void modifierResponse(Response r) {
		em.merge(r);
	}

	@Override
	public List<Response> listResponseByTopicId(Long idTopic, int position,
			int nb_response) {
		Query req = em.createQuery("select r from Response r where idTopic = :x order by r.dateMsg desc");
		req.setParameter("x",idTopic);
//		req.setFirstResult(position);
//		req.setMaxResults(nb_response);
		return req.getResultList();
	}

	@Override
	public Response getResponse(Long idResponse) {
		return em.find(Response.class, idResponse);
	}

	@Override
	public Long getNbResponseByResponseId(Long idResponse) {
		Query req = em.createQuery("select count(r) from Response r where idResponse = :x");
		req.setParameter("x",idResponse);
		return (Long) req.getResultList().get(0);
	}

}
